﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using OpenPhotoAlbum.BusinessLogics;
using OpenPhotoAlbum.Controls;

namespace OpenPhotoAlbum.My
{
	public partial class Album : AlbumPage
	{
		#region Fields
		private const string ID_PHOTO_THUMBNAIL = "hlPhoto";
		private const string ID_PHOTO_THUMBNAIL_IMG = "imgPhoto";
		private const string ID_PHOTO_CAPTION = "lblCaption";
		private const string ID_PHOTO_CREATION_DATE = "lblCreationDate";
		private const string ID_PHOTO_DELETE = "linkBtnDelete";
		private const string ID_PHOTO_COVER = "linkBtnCover";
		private const string ID_PHOTO_CAPTION_TOOLTIP = "ttCaption";
		private const string ID_PHOTO_DELETE_TOOLTIP = "ttDelete";
		private const string ID_PHOTO_COVER_TOOLTIP = "ttCover";
		private Guid _newlyUploadedPhoto = Guid.Empty;
		private const string CMD_DELETE = "del";
		private const string CMD_COVER = "cov";
		private const string TYPE_JPG = ".jpg";
		private const string TYPE_JPEG = ".jpeg";
		private const string TYPE_PNG = ".png";
		private const string TYPE_GIF = ".gif";
		private const string TYPE_ICO = ".ico";
		#endregion

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			this.Title = StringUtility.Format(Resources.Strings.Title_My_Album, UrlContext.AlbumTitle);

			hfAlbumId.Value = UrlContext.AlbumId.ToString();
			hfAlbumTitle.Value = UrlContext.AlbumTitle;

			tabPanels.TabPanelItems.Add(new TabPanelItem()
			{
				Name = Resources.Strings.My_UploadPhoto,
				PanelClientId = pnlUpload.ClientID,
				Visible = false
			});
			tabPanels.TabPanelItems.Add(new TabPanelItem()
			{
				Name = Resources.Strings.SharingAddress,
				PanelClientId = pnlSharingAddress.ClientID,
				Visible = false
			});
			string sharingAddress = UrlContext.BuildSharedAlbumUrl(UrlContext.AlbumId);
			ltrSharingAddress.Text = HttpUtility.HtmlEncode(Links.ToFullPath(sharingAddress));
			hlVisit.Text = Resources.Strings.VisitThisAddress;
			hlVisit.NavigateUrl = sharingAddress;

            lblSelectPhotoFile.Text = string.Format(CultureInfo.CurrentCulture, "{0}{1}", Resources.Strings.My_SelectPhotoFile, Resources.Strings.Colon);
            lblCaption.Text = string.Format(CultureInfo.CurrentCulture, "{0}{1}", Resources.Strings.My_PhotoCaption, Resources.Strings.Colon);
            lblWait.Text = Resources.Strings.My_UploadingPhoto;
			btnUpload.Text = Resources.Strings.My_UploadPhotoSubmit;
			btnUpload.Click += new EventHandler(btnUpload_Click);
            rptPhotos.ItemDataBound += new RepeaterItemEventHandler(rptPhotos_ItemDataBound);
			rptPhotos.ItemCommand += new RepeaterCommandEventHandler(rptPhotos_ItemCommand);

            AfterUploading = false;
		}

		protected override void AppendSiteMapNodes(AlbumSiteMapProvider provider)
		{
			base.AppendSiteMapNodes(provider);

			provider.AppendSiteMapNode(Resources.Strings.SC_Home, Links.Default);
			provider.AppendSiteMapNode(Resources.Strings.My_Home, Links.MyHome);
			provider.AppendSiteMapNode(UrlContext.AlbumTitle, RawUrl);
		}

		protected void btnUpload_Click(object sender, EventArgs e)
		{
			tabPanels.SetVisibleIndex(0);

			if (string.IsNullOrEmpty(fileUpload.FileName)) { return; }

			string caption = tbCaption.Text;

			if (string.IsNullOrEmpty(caption))
				caption = System.IO.Path.GetFileNameWithoutExtension(fileUpload.FileName);

			string ext = System.IO.Path.GetExtension(fileUpload.FileName);
			if (!StringUtility.CompareIgnoreCase(ext, TYPE_JPG)
				&& !StringUtility.CompareIgnoreCase(ext, TYPE_JPEG)
				&& !StringUtility.CompareIgnoreCase(ext, TYPE_PNG)
				&& !StringUtility.CompareIgnoreCase(ext, TYPE_GIF)
				&& !StringUtility.CompareIgnoreCase(ext, TYPE_ICO))
			{
				JsMsgBox.Show(this, Resources.Strings.My_BadFileType);
				return;
			}

			try
			{
				PhotoManager.Instance.SavePhoto(UrlContext.AlbumId, caption, fileUpload.FileBytes);
			}
			catch (ArgumentException)
			{
				JsMsgBox.Show(this, Resources.Strings.SystemError);
				return;
			}

			LoadPhotos();

            AfterUploading = true;
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			LoadPhotos();
		}

		protected void rptPhotos_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			DbAccess.Photo photo = e.Item.DataItem as DbAccess.Photo;
			if (photo == null) { return; }

			HyperLink hlPhoto = (HyperLink)e.Item.FindControl(ID_PHOTO_THUMBNAIL);
			Image imgPhoto = (Image)e.Item.FindControl(ID_PHOTO_THUMBNAIL_IMG);
			InplaceEditLabel lblCaption = (InplaceEditLabel)e.Item.FindControl(ID_PHOTO_CAPTION);
			Label lblCreationDate = (Label)e.Item.FindControl(ID_PHOTO_CREATION_DATE);
			AlbumLinkButton linkBtnDelete = (AlbumLinkButton)e.Item.FindControl(ID_PHOTO_DELETE);
			AlbumLinkButton linkBtnCover = (AlbumLinkButton)e.Item.FindControl(ID_PHOTO_COVER);
			TooltipExtender ttCaption = (TooltipExtender)e.Item.FindControl(ID_PHOTO_CAPTION_TOOLTIP);
			TooltipExtender ttDelete = (TooltipExtender)e.Item.FindControl(ID_PHOTO_DELETE_TOOLTIP);
			TooltipExtender ttCover = (TooltipExtender)e.Item.FindControl(ID_PHOTO_COVER_TOOLTIP);

			hlPhoto.NavigateUrl = UrlContext.BuildMyPhotoUrl(UrlContext.HomePageNumber, UrlContext.AlbumPageNumber, photo.PhotoId, photo.PhotoTitle);
			imgPhoto.ImageUrl = UrlContext.BuildPhotoPipeUrl(photo.PhotoId, BusinessLogics.PhotoTypes.Thumbnail);
			imgPhoto.BorderWidth = new Unit(1, UnitType.Pixel);

			lblCaption.Text = photo.PhotoTitle;
			lblCaption.ContextData1 = photo.PhotoId.ToString();
			lblCaption.ContextData2 = hlPhoto.ClientID;
            lblCaption.TooltipBehaviorId = ttCaption.BehaviorID;
			linkBtnDelete.Text = Resources.Strings.Delete;
			linkBtnDelete.CommandName = CMD_DELETE;
			linkBtnDelete.CommandArgument = photo.PhotoId.ToString();
			linkBtnDelete.OnClientClick = StringUtility.GetConfirmJs(Resources.Strings.My_Confirm_DeletePhoto);
			linkBtnCover.Text = Resources.Strings.My_Photo_Cover;
			linkBtnCover.CommandName = CMD_COVER;
			linkBtnCover.CommandArgument = photo.PhotoId.ToString();
			linkBtnCover.Enabled = !photo.IsAlbumCover;
			ttCaption.Text = Resources.Strings.Tooltip_ClickToEdit;
			ttCaption.ParentElementId = upPhotos.ClientID;
			ttDelete.Text = Resources.Strings.Tooltip_DeletePhoto;
			ttDelete.ParentElementId = upPhotos.ClientID;
			ttCover.Text = Resources.Strings.Tooltip_Cover;
			ttCover.ParentElementId = upPhotos.ClientID;
		}

		protected void rptPhotos_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			if (string.IsNullOrEmpty(e.CommandName) || e.CommandArgument == null)
			{
				return;
			}

			if (e.CommandName == CMD_DELETE)
			{
				Guid photoId = new Guid(e.CommandArgument.ToString());
				BusinessLogics.PhotoManager.Instance.DeletePhoto(photoId);

				LoadPhotos();
			}
			else if (e.CommandName == CMD_COVER)
			{
				Guid photoId = new Guid(e.CommandArgument.ToString());
				BusinessLogics.PhotoManager.Instance.SetAsCover(photoId);

				LoadPhotos();
			}
		}

		private void LoadPhotos()
		{
			IEnumerable<DbAccess.Photo> photos = BusinessLogics.PhotoManager.Instance.GetPhotos(UrlContext.AlbumId);
			rptPhotos.DataSource = photos;
			rptPhotos.DataBind();

			if (photos.Count() == 0) { tabPanels.SetVisibleIndex(0); }
		}

        public bool AfterUploading { get; set; }
	}
}
